package king.dominic.jlibrary.view;

import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by king on 2016/5/16.
 */
public class ImagePagerAdapter extends PagerAdapter {
    private List<ImageView> imageViews;
    private AdapterView.OnItemClickListener listener;

    public ImagePagerAdapter(Context context, List<Integer> resIds) {
        if (resIds == null)
            return;
        imageViews = new ArrayList<>();
        int i = 0;
        for (int resId : resIds) {
            ImageView imageView = new ImageView(context);
            imageView.setImageResource(resId);
            imageView.setScaleType(ImageView.ScaleType.FIT_XY);
            imageView.setOnClickListener(new OnClick(imageView, i++, resId));
            imageViews.add(imageView);
        }
    }

    class OnClick implements View.OnClickListener {
        private final int position;
        private final View view;
        private final long id;

        OnClick(View view, int position, long id) {
            this.view = view;
            this.position = position;
            this.id = id;
        }

        @Override
        public void onClick(View v) {
            if (listener != null)
                listener.onItemClick(null, view, position, id);
        }
    }

    @Override
    public int getCount() {
        return imageViews.size();
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view == object;
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        container.addView(imageViews.get(position));
        return imageViews.get(position);
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        container.removeView((View) object);
    }

    public void setOnItemClickListener(AdapterView.OnItemClickListener listener) {
        this.listener = listener;
    }
}
